package com.jaya.budan.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.jaya.budan.R;
import com.jaya.budan.base.BaseActivity;
import com.jaya.budan.base.MyApplication;
import com.jaya.budan.bean.User_Limit;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.fragment.NearByFragment;
import com.jaya.budan.thirdpush.HUAWEIHmsMessageService;
import com.jaya.budan.thirdpush.OfflineMessageDispatcher;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.Utils;
import com.jaya.budan.utils.VolleyUtil;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMElem;
import com.tencent.imsdk.TIMElemType;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMImageElem;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMMessageListener;
import com.tencent.imsdk.TIMTextElem;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.v2.V2TIMConversation;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMOfflinePushInfo;
import com.tencent.imsdk.v2.V2TIMSendCallback;
import com.tencent.liteav.trtcaudiocalldemo.ui.audiolayout.TRTCAudioLayout;
import com.tencent.qcloud.tim.uikit.component.AudioPlayer;
import com.tencent.qcloud.tim.uikit.component.NoticeLayout;
import com.tencent.qcloud.tim.uikit.component.TitleBarLayout;
import com.tencent.qcloud.tim.uikit.modules.chat.ChatLayout;
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo;
import com.tencent.qcloud.tim.uikit.modules.chat.base.OfflineMessageBean;
import com.tencent.qcloud.tim.uikit.modules.chat.layout.input.InputLayout;
import com.tencent.qcloud.tim.uikit.modules.chat.layout.inputmore.InputMoreActionUnit;
import com.tencent.qcloud.tim.uikit.modules.chat.layout.message.MessageLayout;
import com.tencent.qcloud.tim.uikit.modules.conversation.ConversationManagerKit;
import com.tencent.qcloud.tim.uikit.modules.message.MessageInfo;
import com.tencent.qcloud.tim.uikit.utils.FileUtil;
import com.tencent.qcloud.tim.uikit.utils.TUIKitConstants;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.tencent.imsdk.v2.V2TIMManager.V2TIM_STATUS_LOGINED;

public class Chat_Activity extends BaseActivity implements View.OnClickListener, ConversationManagerKit.MessageUnreadWatcher {

    private RelativeLayout back;
    private String access_token, roomId;
    private TextView tv_chat_nickname;
    private ImageView iv_chat_icon;
    private EditText et_chat;
    private Button btn_chat_send_mes;
    private ChatInfo mChatInfo;
    private User_Limit user_limit;
    private ChatLayout chat_layout;
    private TIMConversation conversation;
    private int position;
    public static Activity activity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = this;
        setContentView(R.layout.activity_chat);
        Intent intent = getIntent();
        access_token = intent.getStringExtra("access_token");
        roomId = intent.getStringExtra("roomId");
        position = intent.getIntExtra("position", 0);
        mChatInfo = (ChatInfo) intent.getSerializableExtra("chatInfo");
        user_limit = (User_Limit) intent.getSerializableExtra("user_limit");
        back = findViewById(R.id.back);
        tv_chat_nickname = findViewById(R.id.tv_chat_nickname);
        iv_chat_icon = findViewById(R.id.iv_chat_icon);
        et_chat = findViewById(R.id.et_chat);
        btn_chat_send_mes = findViewById(R.id.btn_chat_send_mes);
        back.setOnClickListener(this);
        btn_chat_send_mes.setOnClickListener(this);
        iv_chat_icon.setOnClickListener(this);
        FileUtil.initPath(); // 从application移入到这里，原因在于首次装上app，需要获取一系列权限，如创建文件夹，图片下载需要指定创建好的文件目录，否则会下载本地失败，聊天页面从而获取不到图片、表情
        // 未读消息监视器
        ConversationManagerKit.getInstance().addUnreadWatcher(Chat_Activity.this);
//        GroupChatManagerKit.getInstance();
        Utils.canDrawOverlays(Chat_Activity.this, false);//权限检查
        initView();
    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        chat_layout = findViewById(R.id.chat_layout);
        //单聊组件的默认UI和交互初始化
        chat_layout.initDefault();
        //需要聊天的基本信息
        chat_layout.setChatInfo(mChatInfo);
        chat_layout.getTitleBar().setVisibility(View.GONE);
        //获取单聊面板的标题栏
//        TitleBarLayout mTitleBar = chat_layout.getTitleBar();
        //单聊面板标记栏返回按钮点击事件，这里需要开发者自行控制
//        mTitleBar.setOnLeftClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                finish();
//            }
//        });
//        mTitleBar.setBackgroundColor(Color.parseColor("#ffffff"));
//        mTitleBar.setLeftIcon(R.mipmap.iv_return);
//        mTitleBar.setRightIcon(R.mipmap.iv_main_chat);
        if (mChatInfo != null){
//            mTitleBar.setTitle("" + mChatInfo.getChatName(), TitleBarLayout.POSITION.MIDDLE);
            tv_chat_nickname.setText("" + mChatInfo.getChatName());
            if (mChatInfo.getType() == V2TIMConversation.V2TIM_C2C) {
//                mTitleBar.setOnRightClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        //没用
//                    }
//                });
            }
        }
        MessageLayout messageLayout = chat_layout.getMessageLayout();
//        messageLayout.setBackground(new ColorDrawable(0xB0E2FF00));//设置聊天背景
        messageLayout.setBackgroundColor(Color.parseColor("#B0E2FF"));//设置聊天背景
        // 设置默认头像，默认与朋友与自己的头像相同
//        messageLayout.setAvatar(R.mipmap.fill_person_icon);//没用，先注释掉
        // 设置头像圆角，不设置则默认不做圆角处理
        messageLayout.setAvatarRadius(10);
        // 设置头像大小
        messageLayout.setAvatarSize(new int[]{18, 18, 18, 18});

        // 聊天界面设置头像和昵称
//        if (!TextUtils.isEmpty(V2TIMConversation.getFaceUrl())) {
//            List<Object> urllist = new ArrayList<>();
//            urllist.add(msg.getFaceUrl());
//            if (isForwardMode) {
//                leftUserIcon.setIconUrls(urllist);
//            } else {
//                if (msg.isSelf()) {
//                    rightUserIcon.setIconUrls(V2TIMConversation);
//                } else {
//                    leftUserIcon.setIconUrls(urllist);
//                }
//            }
//        } else {
//            rightUserIcon.setIconUrls(null);
//            leftUserIcon.setIconUrls(null);
//        }
        TIMUserProfile profile = TIMFriendshipManager.getInstance().queryUserProfile(mChatInfo.getChatName());
        if (profile == null) {
//            tv_chat_nickname.setText(msg.getFromUser());
        } else {
//            tv_chat_nickname.setText(!ToolUtils.isEmpty(profile.getNickName()) ? profile.getNickName() : msg.getFromUser());
//            if (!ToolUtils.isEmpty(profile.getFaceUrl()) && !messageLayout.isSelf()) {
//                List<String> urllist = new ArrayList<>();
//                urllist.add(profile.getFaceUrl());
//                leftUserIcon.setIconUrls(urllist);
//                urllist.clear();
//            }
        }
        TIMUserProfile selfInfo = TIMFriendshipManager.getInstance().queryUserProfile(TIMManager.getInstance().getLoginUser());
//        if (profile != null && msg.isSelf()) {
//            if (!ToolUtils.isEmpty(selfInfo.getFaceUrl())) {
//                List<String> urllist = new ArrayList<>();
//                urllist.add(profile.getFaceUrl());
//                rightUserIcon.setIconUrls(urllist);
//                urllist.clear();
//            }
//        }
        // 设置自己聊天气泡的背景
        messageLayout.setRightBubble(getResources().getDrawable(R.drawable.login_login2));
        // 设置朋友聊天气泡的背景
        messageLayout.setLeftBubble(getResources().getDrawable(R.drawable.login_login2));
        ////// 设置昵称样式（对方与自己的样式保持一致）//////
        messageLayout.setNameFontSize(12);
        messageLayout.setNameFontColor(R.color.chat_name);
        // 设置聊天内容字体大小，朋友和自己用一种字体大小
        messageLayout.setChatContextFontSize(15);
        // 设置自己聊天内容字体颜色
        messageLayout.setRightChatContentFontColor(0xA9A9A900);
        // 设置朋友聊天内容字体颜色
        messageLayout.setLeftChatContentFontColor(0xA020F000);
        // 设置聊天时间线的背景
        messageLayout.setChatTimeBubble(new ColorDrawable(0x8B691400));
        // 设置聊天时间的字体大小
        messageLayout.setChatTimeFontSize(20);
        // 设置聊天时间的字体颜色
        messageLayout.setChatTimeFontColor(0xEE00EE00);
        // 设置提示的背景
        messageLayout.setTipsMessageBubble(new ColorDrawable(0xA020F000));
        // 设置提示的字体大小
        messageLayout.setTipsMessageFontSize(20);
        // 设置提示的字体颜色
        messageLayout.setTipsMessageFontColor(0x7CFC0000);
        messageLayout.setOnItemClickListener(new MessageLayout.OnItemClickListener() {
            @Override
            public void onMessageLongClick(View view, int position, MessageInfo messageInfo) {
                //因为adapter中第一条为加载条目，位置需减1
                chat_layout.getMessageLayout().showItemPopMenu(position - 1, messageInfo, view);
            }

            @Override
            public void onUserIconClick(View view, int position, MessageInfo messageInfo) {
                if (null == messageInfo) {
                    return;
                }
                ChatInfo info = new ChatInfo();
                info.setId(messageInfo.getFromUser());
                Intent intent = new Intent(MyApplication.getInstance2(), Chat_Activity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(TUIKitConstants.ProfileType.CONTENT, info);
                MyApplication.getInstance2().startActivity(intent);
            }
        });
//        NoticeLayout noticeLayout = chat_layout.getNoticeLayout();
//        // 可以使通知区域一致展示
//        noticeLayout.alwaysShow(true);
//        // 设置通知主题
//        noticeLayout.getContent().setText("现在插播一条广告");
//        // 设置通知提醒文字
//        noticeLayout.getContentExtra().setText("参看有奖");
//        // 设置通知的点击事件
//        noticeLayout.setOnNoticeClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                ToolUtils.showToast(Chat_Activity.this, "赏白银五千两");
//            }
//        });
        InputLayout inputLayout = chat_layout.getInputLayout();
// 隐藏拍照并发送
//        inputLayout.disableCaptureAction(true);
// 隐藏发送文件
//        inputLayout.disableSendFileAction(true);
// 隐藏发送图片
//        inputLayout.disableSendPhotoAction(true);
// 隐藏摄像并发送
//        inputLayout.disableVideoRecordAction(true);
//        inputLayout.enableAudioCall();
//        inputLayout.enableVideoCall();
        TRTCAudioLayout audioLayout = new TRTCAudioLayout(Chat_Activity.this);
        audioLayout.setUserId("1");
        // TODO 可以自己增加一些功能，可以打开下面代码测试
        // 增加一个欢迎提示富文本
        InputMoreActionUnit unit = new InputMoreActionUnit();
        unit.setIconResId(R.drawable.file_icon);
        unit.setTitleId(1);
        unit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToolUtils.showToast(Chat_Activity.this, "file_icon");
            }
        });
//        inputLayout.addAction(unit);
        conversation = TIMManager.getInstance().getConversation(
                TIMConversationType.C2C,    //会话类型：单聊
                roomId + "");
//        TIMManager.getInstance().getConversation(
//                TIMConversationType.Group,      //会话类型：群组
//                roomId);
        TIMManager.getInstance().addMessageListener(new TIMMessageListener() {//消息监听器
            @Override
            public boolean onNewMessages(List<TIMMessage> msgs) {//收到新消息
                for (int z= 0; z < msgs.size(); z++){
                    TIMMessage msg = msgs.get(z);
                    for(int i = 0; i < msg.getElementCount(); ++i) {
                        TIMElem elem = msg.getElement(i);
                        TIMElemType elemType = elem.getType();//获取当前元素的类型
                        Log.d("", "elem type: " + elemType.name());
                        if (elemType == TIMElemType.Text) {//处理文本消息
                            TIMTextElem elemnew = (TIMTextElem) elem;
                            ToolUtils.showToast(Chat_Activity.this, msg.getSender()+":"+elemnew.getText());
                        } else if (elemType == TIMElemType.Image) { //处理图片消息
                            TIMImageElem elem4 = (TIMImageElem) elem;
                            ToolUtils.showToast(Chat_Activity.this, msg.getSender()+":"+elem4.getPath());
                        }//...处理更多消息
                    }
                }
                //消息的内容解析请参考消息收发文档中的消息解析说明
                return true; //返回true将终止回调链，不再调用下一个新消息监听器
            }
        });
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_chat_icon:
//                Intent intent = new Intent(MyApplication.getInstance2(), Chat_Activity.class);
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                intent.putExtra(TUIKitConstants.ProfileType.CONTENT, mChatInfo);
//                MyApplication.getInstance2().startActivity(intent);
                Intent intent = new Intent(Chat_Activity.this, Chat_Msg_Set_Activity.class);
                intent.putExtra("access_token", access_token);
                intent.putExtra("user_limit", user_limit);
                intent.putExtra("position", position);
                startActivity(intent);
                break;
            case R.id.btn_chat_send_mes:
                MessageInfo info = new MessageInfo();
                info.setExtra(et_chat.getText().toString().trim());
                chat_layout.sendMessage(info, true);
                break;
            case R.id.back:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Intent intent = getIntent();
        mChatInfo = (ChatInfo) intent.getSerializableExtra("chatInfo");
        if (mChatInfo == null) {
            return;
        }
        initView();
//        // TODO 通过api设置ChatLayout各种属性的样例
//        ChatLayoutHelper helper = new ChatLayoutHelper(this);
//        helper.customizeChatLayout(chat_layout);
    }

    @Override
    protected void onPause() {
        super.onPause();
        AudioPlayer.getInstance().stopPlay();
    }

    /**
     * 网络请求
     */
    private void postData() {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, RequestConnect.gr_xyf_Url + access_token + "&limit=10", null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("xinyun", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONArray info = jsonObject.getJSONArray("info");
                    } else {
                        ToolUtils.showToast(Chat_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(Chat_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    @Override
    public void updateUnread(int count) {
        if (count > 0) {
//            mMsgUnread.setVisibility(View.VISIBLE);//角标
        } else {
//            mMsgUnread.setVisibility(View.GONE);
        }
        String unreadStr = "" + count;
        if (count > 100) {
            unreadStr = "99+";
        }
//        mMsgUnread.setText(unreadStr);
        // 华为离线推送角标
        HUAWEIHmsMessageService.updateBadge(this, count);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (chat_layout != null) {
            chat_layout.exitChat();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        chat(intent);
    }

    private void chat(Intent intent) {
        Bundle bundle = intent.getExtras();
        ChatInfo mChatInfo = new ChatInfo();
        Log.i("main", "bundle: " + bundle + " intent: " + intent);
        if (bundle == null) {
            //刷新
            return;
        }
        OfflineMessageBean bean = OfflineMessageDispatcher.parseOfflineMessage(intent);
        if (bean != null) {
            mChatInfo.setType(bean.chatType);
            mChatInfo.setId(bean.sender);
            bundle.putSerializable("chat_info", mChatInfo);
            Log.i("main", "offline mChatInfo: " + mChatInfo);
        } else {
            mChatInfo = (ChatInfo) bundle.getSerializable("chat_info");
            if (mChatInfo == null) {
                //刷新
                return;
            }
        }
        if (V2TIMManager.getInstance().getLoginStatus() == V2TIM_STATUS_LOGINED) {
            NearByFragment mChatFragment = new NearByFragment();
            mChatFragment.setArguments(bundle);
            getSupportFragmentManager().beginTransaction().replace(R.id.main_fragment, new NearByFragment()).commitAllowingStateLoss();
        } else {
            //刷新
        }
    }
}
